<!DOCTYPE html>
<html lang="zh">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" />
    <title>数据源列表 - 浩瀚后台管理系统模板</title>
    <link rel="icon" href="favicon.ico" type="image/ico">
    <meta name="keywords" content="Sql-Web,浩瀚,后台模板,后台管理系统,浩瀚HTML模板">
    <meta name="description" content="Sql-Web是一个基于Bootstrap v3.3.7的后台管理系统的HTML模板。">
    <meta name="author" content="浩瀚">
    <link href="css/bootstrap.min.css" rel="stylesheet">
    <link href="css/materialdesignicons.min.css" rel="stylesheet">
    <link href="css/style.min.css" rel="stylesheet">
    <style>
        /* 自定义滚动条容器 */
        .table-responsive-scroll {
            overflow-x: auto !important;
            overflow-y: hidden !important;
        }

        /* 自定义模态框宽度 */
        @media (min-width: 992px) {
            .modal-lg {
                width: 90%;
                /* 或者你想要的任何宽度 */
            }
        }

        /* 针对小屏幕，也确保模态框可以滚动 */
        @media (max-width: 991px) {
            .modal-lg {
                width: 100%;
                max-width: none;
            }
        }

        td {
            max-width: 150px;
            /* 设置单元格最大宽度 */
            overflow: hidden;
            /* 隐藏超出部分 */
            text-overflow: ellipsis;
            /* 显示省略号 */
            white-space: nowrap;
            /* 不换行 */
        }

        td:hover {
            overflow: visible;
            white-space: normal;
            background: #FFF;
            z-index: 100;
        }
    </style>



</head>

<body>
    <div class="container-fluid p-t-15">

        <div class="row">
            <div class="col-lg-12">
                <div class="card">
                    <div class="card-toolbar clearfix">
                        <form class="pull-right search-bar" method="get" action="#!" role="form">
                            <div class="input-group">
                            </div>
                        </form>
                    </div>
                    <div class="card-body">

                        <div class="table-responsive">
                            <table class="table table-bordered">
                                <thead>
                                    <tr>
                                        <th>
                                            <label class="lyear-checkbox checkbox-primary">
                                                <input type="checkbox" id="check-all"><span></span>
                                            </label>
                                        </th>
                                        <th>编号</th>
                                        <th>数据源名称</th>
                                        <th>执行语句</th>
                                        <th>执行结果</th>
                                        <th>执行时间</th>
                                        <th>操作</th>
                                    </tr>
                                </thead>
                                <tbody id="sql-list">
                                    <!-- 动态数据将插入此处 -->
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>

        </div>
    </div>

    <!-- Result Modal -->
    <div class="modal fade" id="resultModal" tabindex="-1" role="dialog" aria-labelledby="resultModalLabel">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="resultModalLabel">执行结果</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <!-- 这里添加一个新的div作为滚动容器 -->
                    <div class="table-responsive-scroll">
                        <!-- 文件内容表格将显示在这里 -->
                    </div>
                </div>
                <div class="modal-footer">
                    <nav aria-label="Table pagination" id="table-pagination">
                        <ul class="pagination">
                            <!-- 分页按钮将在这里动态生成 -->
                        </ul>
                    </nav>
                </div>
            </div>
        </div>

    </div>


    <script type="text/javascript" src="js/jquery.min.js"></script>
    <script type="text/javascript" src="js/bootstrap.min.js"></script>
    <script type="text/javascript" src="js/main.min.js"></script>
    <script type="text/javascript">

        // 发起删除数据源的 AJAX 请求的函数
        function deleteSqlHis(id) {
            $.ajax({
                url: "/sql/removeSqlHis",
                type: "POST",
                contentType: "application/json", // 设置请求头内容类型为 JSON
                data: JSON.stringify({ "id": id }), // 将对象转为 JSON 字符串
                success: function (response) {
                    if (response.code === 200) {
                        // 删除成功后的操作，比如重新加载数据源列表
                        fetchDataSourceList();
                        //alert(name + ' 数据源已成功删除。');
                    } else {
                        // 删除失败的操作
                        displayAlertModal('删除失败: ' + response.msg);
                    }
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    // 请求失败时的处理逻辑
                    displayAlertModal('删除数据源请求失败: ' + textStatus);
                }
            });
        }
        // 更新表格函数
        function updateDataSourceTable(data) {
            var tbody = $('#sql-list');
            tbody.empty(); // 清空现有的数据

            data.forEach(function (dataSource) {
                var row = `<tr>
                <td>
                    <label class="lyear-checkbox checkbox-primary">
                        <input type="checkbox" name="ids[]" value="${dataSource.id}"><span></span>
                    </label>
                </td>
                <td>${dataSource.id}</td>
                <td>${dataSource.dataSourceName}</td>
                <td>${dataSource.sqlStatement}</td>
                <td>${dataSource.resultFile}</td>
                <td>${dataSource.createTime}</td>
                <td>
                    <div class="btn-group">
                    <a class="btn btn-xs btn-default view-btn" href="#!" title="查看" data-toggle="tooltip" data-id="${dataSource.id}"><i class="mdi mdi-eye"></i></a>
                    <a class="btn btn-xs btn-default" href="#!" title="删除" data-toggle="tooltip" onclick="deleteSqlHis('${dataSource.id}')"><i class="mdi mdi-window-close"></i></a>

                    </div>
                </td>
            </tr>`;
                tbody.append(row);
            });
        }

        // 请求数据源列表
        function fetchDataSourceList() {
            $.ajax({
                url: "/sql/list",
                type: "POST",
                success: function (response) {
                    if (response.code === 200 && response.data) {
                        updateDataSourceTable(response.data);
                    } else {
                        // 处理错误或者显示一些消息
                        console.error('获取数据失败:', response.msg);
                    }
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    // 请求失败时的处理逻辑
                    console.error('请求数据源列表失败:', textStatus, errorThrown);
                }
            });
        }

        // 绑定查看按钮的点击事件
        $('#sql-list').on('click', '.view-btn', function () {
            var id = $(this).data('id'); // 获取ID
            $.ajax({
                url: "/sql/viewResult/" + id,
                type: "GET",
                success: function (csvString) {
                    if (typeof csvString !== 'undefined' && csvString) {
                        var pageSize = 10; // 设置每页显示行数
                        var currentPage = 1; // 初始化当前页为第一页

                        // 解析CSV数据并生成HTML表格
                        var csvData = csvToTableData(csvString, pageSize, currentPage);
                        var totalRows = csvData.totalRows;
                        var totalPages = Math.ceil(totalRows / pageSize); // 计算总页数

                        // 在表格滚动容器中显示当前页的表格
                        $('#resultModal .table-responsive-scroll')
                            .html(csvData.tableHtml).data('csv', csvString); // 将CSV字符串保存到data属性;

                        // 生成并显示分页按钮
                        updatePagination(totalPages, currentPage);

                        // 显示模态框
                        $('#resultModal').modal('show');
                    } else {
                        // 处理csvString未定义或为空的情况
                        console.error('csvString is undefined or empty.');
                    }
                },
                error: function () {
                    console.error('无法获取文件内容');
                }
            });
        });

        // 解析CSV数据并返回表格HTML和总行数
        function csvToTableData(csvString, pageSize, currentPage) {
            var lines = csvString.split('\n');
            var headers = lines[0].split(',');
            var totalRows = lines.length - 1; // 减去标题行
            var startRow = (currentPage - 1) * pageSize + 1; // 计算起始行号
            var endRow = startRow + pageSize - 1; // 计算结束行号
            endRow = endRow > totalRows ? totalRows : endRow; // 如果超出总行数，则调整结束行号

            // 生成HTML表格
            var tableHtml = '<table class="table table-bordered"><thead><tr>';
            headers.forEach(function (header) {
                tableHtml += '<th>' + header.trim() + '</th>';
            });
            tableHtml += '</tr></thead><tbody>';

            for (var i = startRow; i <= endRow; i++) {
                if (lines[i]) { // 确保不超出数组界限
                    var row = lines[i].split(',');
                    tableHtml += '<tr>';
                    row.forEach(function (cell) {
                        tableHtml += '<td>' + cell.trim() + '</td>';
                    });
                    tableHtml += '</tr>';
                }
            }
            tableHtml += '</tbody></table>';

            return { tableHtml: tableHtml, totalRows: totalRows };
        }

        function updatePagination(totalPages, currentPage) {
            var maxPageButtons = 5; // 最多显示的分页按钮数
            var halfWay = Math.ceil(maxPageButtons / 2);

            var paginationHtml = '';
            var startPage = currentPage - halfWay + 1;
            startPage = Math.max(startPage, 1);
            var endPage = startPage + maxPageButtons - 1;
            endPage = Math.min(endPage, totalPages);

            if (endPage - startPage < maxPageButtons - 1) {
                startPage = Math.max(endPage - maxPageButtons + 1, 1);
            }

            // 添加"首页"和"上一页"按钮
            paginationHtml += `<li class="page-item ${currentPage === 1 ? 'disabled' : ''}">
                <a class="page-link" href="#" aria-label="First" data-page="1">
                    <span aria-hidden="true">首页</span>
                </a>
            </li>`;
            paginationHtml += `<li class="page-item ${currentPage === 1 ? 'disabled' : ''}">
                <a class="page-link" href="#" aria-label="Previous" data-page="${currentPage - 1}">
                    <span aria-hidden="true">上一页</span>
                </a>
            </li>`;

            // 添加分页按钮
            for (var i = startPage; i <= endPage; i++) {
                paginationHtml += `<li class="page-item ${i === currentPage ? 'active' : ''}">
                    <a class="page-link" href="#" data-page="${i}">${i}</a>
                </li>`;
            }

            // 添加"下一页"和"末页"按钮
            paginationHtml += `<li class="page-item ${currentPage === totalPages ? 'disabled' : ''}">
                <a class="page-link" href="#" aria-label="Next" data-page="${currentPage + 1}">
                    <span aria-hidden="true">下一页</span>
                </a>
            </li>`;
            paginationHtml += `<li class="page-item ${currentPage === totalPages ? 'disabled' : ''}">
                <a class="page-link" href="#" aria-label="Last" data-page="${totalPages}">
                    <span aria-hidden="true">末页</span>
                </a>
            </li>`;

            $('#table-pagination .pagination').html(paginationHtml).find('.page-link').on('click', function (e) {
                e.preventDefault();
                var selectedPage = parseInt($(this).data('page'));
                if (selectedPage !== currentPage && selectedPage > 0 && selectedPage <= totalPages) {
                    var csvData = csvToTableData($('#resultModal .table-responsive-scroll').data('csv'), 10, selectedPage);
                    $('#resultModal .table-responsive-scroll').html(csvData.tableHtml);
                    updatePagination(totalPages, selectedPage);
                }
            });
        }


        $(document).ready(function () {
            // 页面加载完毕后立即获取数据源列表
            fetchDataSourceList();
        });


    </script>

</body>

</html>